// pages/index.js
import dayjs from '../../utils/dayjs'
var QQMapWX = require("../../utils/qqmap-wx-jssdk.min");//注意一定要相对路径，绝对路径可能会报错。
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    key: "SEKRTBhf6hxyY8d2K",
    selectDate: "",
    week: "",
    city: {
      longitude: "",
      latitude: "",
      markers: [],
      location: {
        name: "获取位置信息"
      },
      weather: [],
    },
    todoList: [],
    travelList: [],
    pickerList: [],
    userInfo:{
      nickName: "获取用户信息"
    }, // 用户基本信息
    canIUseGetUserProfile: true,
  },
  // 获取用户信息回调
  getUserProfile(e) {
    wx.getUserProfile({
      desc: '音乐', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          canIUseGetUserProfile:false
        })
      },
      fail:(error) => {
        console.log(error)
      }
    })
  },
  goRouter(e){
    let url = e.currentTarget.dataset['url']
    wx.navigateTo({
      url,
    })
  },
  getLocalFunc() {
    var that = this;
    wx.getLocation({
      type: "wgs84",
      success: async function (res) {
        let {
          latitude,
          longitude
        } = res
        //  return;
        const data = await that.getCityWeather(res)
        let getData = {
          latitude,
          longitude,
          markers: [{
            // iconPath: "/images/location.png", // 标记图标路径
            id: 0,
            latitude,
            longitude,
            width: 20,
            height: 30
          }],
          location: {
            ...data.data.results[0].location,
          },
          weather: [...data.data.results[0].daily.map(item => ({
            ...item,
            iDate: item.date.split('-')
          }))]
        }
        that.setData({
          city: {
            ...getData
          }
        })
        wx.setStorageSync('cityMap', {
          ...getData
        })
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },
  getCityWeather({
    latitude,
    longitude
  }) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://api.seniverse.com/v3/weather/daily.json?key=${this.data.key}&location=${latitude}:${longitude}&language=zh-Hans&unit=c&start=0&days=7`,
        success: res => {
          resolve(res)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  async getTodoList() {
    const res = await wx.cloud.database().collection('todoList').where({
      userId: wx.getStorageSync('uid'),
      todoTime: this.data.selectDate,
      tableType: "todo"
    }).get()
    const dateTag = await wx.cloud.database().collection('todoList').where({
      userId: wx.getStorageSync('uid'),
      tableType: "todo"
    }).get()
    this.setData({
      todoList: [...res.data]
    })
  },
  async getTravelList() {
    const res = await wx.cloud.database().collection('travel').where({
      travelUserId: wx.getStorageSync('uid'),
      travelTime: this.data.selectDate,
    }).get()
    let pickerList = wx.getStorageSync('dictList').filter(item => item.dictValue == 'tranleType')[0]['dictJson'].map(item => item.key) ?? []
    this.setData({
      travelList: [...res.data].map(item => ({
        ...item,
        date: `${item.travelTime.split("-")[1]}-${item.travelTime.split("-")[2]}`,
        travelTypes: pickerList.filter((it, index) => index == item.travelType)[0]
      }))
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.pickerList = wx.getStorageSync('dictList').filter(item => item.dictValue == 'tranleType')[0]['dictJson'].map(item => item.key) ?? []
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    if (this.data.city.longitude == '') {
      this.getLocalFunc()
    }
    // 在需要获取用户信息的页面或组件中调用wx.getUserInfo方法
    // wx.getUserInfo({
    //   success: function (res) {
    //     var userInfo = res.userInfo;
    //     var userName = userInfo.nickName; // 用户名
    //     var avatarUrl = userInfo.avatarUrl; // 用户头像

    //     console.log('用户名：', userName);
    //     console.log('用户头像：', avatarUrl);
    //   },
    //   fail: function (res) {
    //     console.log('获取用户信息失败:', res);
    //   }
    // });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      selectDate: dayjs(new Date()).format("YYYY-MM-DD"),
      week: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][dayjs().day()]
    })
    this.getTodoList()
    this.getTravelList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})